package com.gexiaobao.pigeon.ui.fragment.mall

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Rect
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.model.param.AddOrReGoodsParam
import com.gexiaobao.pigeon.app.model.param.CancelOrderParam
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentShopOrderListBinding
import com.gexiaobao.pigeon.ui.adapter.HotGoodsAdapter
import com.gexiaobao.pigeon.ui.adapter.ShopOrderListAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.ui.mall.MallViewModel
import com.kingja.loadsir.core.LoadService
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import java.util.Date

/**
 * @Author      : hxw
 * @Date        : 2023/6/20 14:55
 * @Describe    : 我的订单列表
 */
class FragmentShopOrderList : BaseFragment<MallViewModel, FragmentShopOrderListBinding>() {

    private var index = -1
    private val mAdapter: ShopOrderListAdapter by lazy { ShopOrderListAdapter(arrayListOf(), Date()) }
    private val mHotAdapter: HotGoodsAdapter by lazy { HotGoodsAdapter(arrayListOf()) }
    private lateinit var dialog: RxDialogDefault
    private lateinit var loadsir: LoadService<Any>
    private var mIsRefresh = true

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    override fun initView(savedInstanceState: Bundle?) {
        index = requireArguments().getInt("index")

        /** 正在热卖 */
        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        mDatabind.swipeRecyclerViewHot.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
                super.getItemOffsets(outRect, view, parent, state)
                outRect.right = Util.dp2px(context, 5f)//右间距5dp
                outRect.left = Util.dp2px(context, 5f)//左间距5dp
                outRect.top = Util.dp2px(context, 5f)//上间距5dp
                outRect.bottom = Util.dp2px(context, 5f)//下间距5dp
            }
        })
        mDatabind.swipeRecyclerViewHot.layoutManager = layoutManager
        mDatabind.swipeRecyclerViewHot.adapter = mHotAdapter

        eventViewModel.toRefreshListShopOrder.observeInFragment(this) {
            onRefresh(true)
        }

        eventViewModel.toNoticePaySuccess.observeInFragment(this) {
            onRefresh(true)
        }

        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, Util.dp2px(context, 10f)))
            it.initFooter {
                //触发加载更多时请求数据
                mViewModel.getMyOrderList(false, index)
            }
        }

        /** 下拉刷新 */
        mDatabind.layoutList.swipeRefreshLayout.init {
            onRefresh(true)
        }

        /** 状态页配置 */
        loadsir = loadServiceInit(mDatabind.layoutList.swipeRefreshLayout) {
            /** 点击重试时触发的操作 */
            onRefresh(true)
        }

        mHotAdapter.setOnItemClickListener { _, _, position ->
            nav().navigateAction(R.id.action_to_fragment_goods_detail, Bundle().apply {
                putString("id", mHotAdapter.data[position].goodsId.toString())
            })
        }

        mAdapter.setOnChildGoodsClickListener(object : ShopOrderListAdapter.OnChildItemClickListener {
            override fun onChildItemClick(position: Int) {
                when (mAdapter.data[position].orderStatus) {
                    0, 1 -> {
                        nav().navigateAction(R.id.action_to_fragment_order_detail, Bundle().apply {
                            putString("orderId", mAdapter.data[position].id.toString())
                            putString("type", "list")
                        })
                    }
                }
            }
        })

        mAdapter.addChildClickViewIds(R.id.llList, R.id.tvItemToPay, R.id.tvItemDelOrder, R.id.shop_order_detail_status)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.shop_order_detail_status -> {
                    nav().navigateAction(R.id.action_to_fragment_merchant_store, Bundle().apply {
                        putInt("shopId", mAdapter.data[position].list[0].shopId)
                    })
                }

                R.id.llList -> {
                    when (mAdapter.data[position].orderStatus) {
                        0, 1 -> {
                            nav().navigateAction(R.id.action_to_fragment_order_detail, Bundle().apply {
                                putString("orderId", mAdapter.data[position].id.toString())
                                putString("type", "list")
                            })
                        }
                    }
                }

                R.id.tvItemToPay -> {
                    when (mAdapter.data[position].orderStatus) {
                        0, 1 -> {
                            nav().navigateAction(R.id.action_to_fragment_order_detail, Bundle().apply {
                                putString("orderId", mAdapter.data[position].id.toString())
                                putString("type", "list")
                            })
                        }

                        9 -> {//再次购买

                        }
                    }
                }

                R.id.tvItemDelOrder -> {
                    cancelOrder(mAdapter.data[position].id, mAdapter.data[position].orderStatus)
                }
            }
        }
    }


    private fun cancelOrder(id: Int, orderStatus: Int) {
        var titleDialog = ""
        when (orderStatus) {
            0, 1 -> {
                titleDialog = "是否取消该订单"
            }

            9 -> {
                titleDialog = "是否删除该订单"
            }
        }
        dialog = RxDialogDefault(context)
        dialog.setTitle(titleDialog)
        dialog.setSureListener {
            showLoading(getString(R.string.loading))
            when (orderStatus) {
                0, 1 -> {
                    val body = CancelOrderParam(orderId = id)
                    mViewModel.cancelOrder(body)
                }

                9 -> {
                    val body = AddOrReGoodsParam(id = id)
                    mViewModel.userDeleteOrder(body)
                }
            }
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        onRefresh(true)

    }

    private fun onRefresh(isRefresh: Boolean) {
        mIsRefresh = isRefresh
        loadsir.showLoading()
        mViewModel.getMyOrderList(isRefresh, index)
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvShopOrderGo) {
            when (it) {
                mDatabind.tvShopOrderGo -> {
                    nav().navigateAction(R.id.action_to_fragment_mall_goods, Bundle().apply {
                        putInt("index", 0)
                    })
                }
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 获取热卖商品列表 */
        mViewModel.HotGoodsListResult.observe(viewLifecycleOwner) {
            if (it.isEmpty()) {
                RxToast.showToast("获取热卖商品失败")
                return@observe
            }
            mHotAdapter.setList(it.list)
            mHotAdapter.notifyDataSetChanged()
        }
        /** 申请退换货 */
        mViewModel.refundResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it.isSuccess) {
                RxToast.success("申请成功")
                eventViewModel.refundReturnResult.value = true
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 删除订单  */
        mViewModel.deleteOrderResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                dialog.dismiss()
                RxToast.showToast("操作成功")
                onRefresh(true)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 取消订单  */
        mViewModel.cancelOrderResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                dialog.dismiss()
                RxToast.showToast("操作成功")
                onRefresh(true)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 获取我的订单列表 */
        mViewModel.shopOrderListResult.observe(viewLifecycleOwner) {
            if (it.isEmpty && mIsRefresh) {
                mDatabind.nestedScrollViewEmptyDataUI.visibility = View.VISIBLE
                mDatabind.layoutList.conList.visibility = View.GONE
                mViewModel.getHotSaleList()
            } else {
                mDatabind.nestedScrollViewEmptyDataUI.visibility = View.GONE
                mDatabind.layoutList.conList.visibility = View.VISIBLE
            }
            loadListData(it, mAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mAdapter.cancelAllTimers()
    }

    companion object {
        fun newInstance(i: Int): FragmentShopOrderList {
            val fragment = FragmentShopOrderList()
            val bundle = Bundle()
            bundle.putInt("index", i)
            fragment.arguments = bundle
            return fragment
        }
    }
}